package main

import (
	"net"
        "fmt"
        "log"
        "time"

	pb "example.com/http-grpc-server/proto/hello_http"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
)

const (
	// Address gRPC服务地址
	Address = "127.0.0.1:50053"
)

// 定义helloHTTPService并实现约定的接口
type helloHTTPService struct{}

// HelloHTTPService 实现服务端接口
var HelloHTTPService = helloHTTPService{}

/**
* @Description: 实现HelloHTTP服务接口
* @Author: liangan
* @Date: 2023-09-02_11:25
 */
func (h helloHTTPService) SayHello(ctx context.Context, req *pb.HelloHTTPRequest) (*pb.HelloHTTPResponse, error) {
	resp := new(pb.HelloHTTPResponse)
	resp.Message = "Hello " + req.Name + "."
        log.Printf("接收到客户端的消息: %v", req.Name)
        time.Sleep(time.Second)
        timeUnix := time.Now().Unix()
        formatTimeStr := time.Unix(timeUnix,0).Format("2006-01-02 15:04:05")
        ms := fmt.Sprintf("好的收到,%s %s", req.Name, formatTimeStr)
        log.Printf("回复客户端的消息: %s", ms)
        resp.Message = ms
	return resp, nil
}

/**
* @Description: grpc服务端
* @Author: liangan
* @Date: 2023-09-02_11:13
 */
func main() {
	listen, err := net.Listen("tcp", Address)
	if err != nil {
           log.Println("failed to listen: %v", err)
	}

	// 实例化grpc Server
	s := grpc.NewServer()

	// 注册HelloHTTPService
	pb.RegisterHelloHTTPServer(s, HelloHTTPService)

        // 启动RPC并监听
        log.Printf("server listening at %v", listen.Addr())
	s.Serve(listen)
}

